<script setup lang="ts">
import { onBeforeUnmount, onMounted, ref } from 'vue';
import { message } from 'ant-design-vue';
import { api } from '@/api/api'; // 假设你有一个 api 实例来处理请求
import { CloseCircleOutlined, FileDoneOutlined, LoadingOutlined, SyncOutlined } from '@ant-design/icons-vue';
import { getIcon } from "@/api/assets/assets";
import { fetchUrlApi } from '@/api/Teacher/resourceApi';
import { fetchCoursesApi } from '@/api/Teacher/courseApi';
// import logo1 from '@/assets/1301.png';
// import logo2 from '@/assets/120.png';
// import logo3 from '@/assets/1401.png';
// import logo4 from '@/assets/117.png';

const logo1 = ref<string>("")
const logo2 = ref<string>("")
const logo3 = ref<string>("")
const logo4 = ref<string>("")

const fetchIcon = async () => {
  try {
    const data = await getIcon([
      '1301.png',
      '120.png',
      '1401.png',
      '117.png',
    ]);
    logo1.value = data['1301.png'];
    logo2.value = data['120.png'];
    logo3.value = data['1401.png'];
    logo4.value = data['117.png'];
  }
  catch (error) {
    console.error('API 调用错误:', error)
  }
}

onMounted(() => {
  fetchIcon()
})

// 状态管理
const data = ref<any[]>([]);
const searchValue = ref<string>('');
const loading = ref(false);
const intervalId = ref<number | null>(null);

// 获取资源状态
const fetchSourcesState = async (searchValue: string, load: boolean) => {
  try {
    loading.value = load;
    const response = await api.get('/java/teacher/StudySpaceTeacher/getAllSourcesState', {});

    data.value = response.data;
  }
  catch (error) {
    message.error('请求失败');
    console.error('Error fetching sources state:', error);
  }
  finally {
    loading.value = false;
  }
};
onMounted(() => {
  fetchSourcesState('', true);
});
// 处理搜索
const handleSearch = (value: string) => {
  searchValue.value = value;
  fetchSourcesState(value, true);
};

// 初始化和轮询
onMounted(() => {
  fetchSourcesState(searchValue.value, true);
  intervalId.value = setInterval(() => {
    fetchSourcesState(searchValue.value, false);
  }, 200000);
});

// 组件卸载前清除轮询
onBeforeUnmount(() => {
  if (intervalId.value !== null)
    clearInterval(intervalId.value);
});

// 定义获取图标的函数
const getStatusIcon = (status: string) => {
  switch (status) {
    case '文档':
      return logo1.value;
    case '音视频':
      return logo2.value;
    case '网页':
      return logo3.value;
    default:
      return logo4.value;
  }
};
// 处理点击事件
// const handleItemClick = async (item: any) => {
//   if (item.web) {
//     window.open(item.web);
//   }
//   else if (item.tag === '文档') {
//     try {
//       const response = await api.get('/java/StudySpaceStudent/getCourseFileUrl', {
//         params: { courseSourceId: item.sourceId, SourceType: '文档' },
//       });
//       const fileUrl = response.data?.msg;
//       if (fileUrl) {
//         localStorage.setItem('pdfUrl', fileUrl);
//         window.open(`/learn/document/${item.sourceId}/${item.courseId}`);
//       }
//     }
//     catch (error) {
//       console.error('Request failed:', error);
//     }
//   }
// };

// // 使用 lodash 的防抖处理条目点击
// const debouncedHandleItemClick = debounce(handleItemClick, 500);

// 处理资源点击事件
const handleWordClick = (item: any) => {
  const PreCourseId = item.courseId;
  const PreFolderId = (BigInt(PreCourseId) + BigInt(1)).toString();
  const resourceId = item.sourceId;
  const path = encodeURIComponent(item.sourcePath);
  const shareUrl = import.meta.env.VITE_LOCAL_IP
  const newTabUrl = `http://${shareUrl}/learn/previewdocument/${PreCourseId}/${PreFolderId}/${resourceId}/${path}`
  window.open(newTabUrl, '_blank');
}
const handleVideoClick = (item: any) => {
  const PreCourseId = item.courseId;
  const PreFolderId = (BigInt(PreCourseId) + BigInt(1)).toString();
  const resourceId = item.sourceId;
  const path = encodeURIComponent(item.sourcePath);
  const shareUrl = import.meta.env.VITE_LOCAL_IP
  const newTabUrl = `http://${shareUrl}/learn/previewvideo/${PreCourseId}/${PreFolderId}/${resourceId}/${path}`
  window.open(newTabUrl, '_blank');
}
const handleItemClickResource = (element: { tag: string }) => {
  // if (element.tag === '文档')
  //   handleWordClick(element);
  // if (element.tag === '音视频')
  //   handleVideoClick(element);
};
</script>

<template>
  <div class="courseManager">
    <a-spin :spinning="loading" size="large">
      <div class="controlc">
        <h2 class="title">
          我的课程
        </h2>
      </div>

      <div class="controls">
        <a-input-search
          v-model:value="searchValue"
          placeholder="搜索"
          class="search"
          enter-button
          @search="handleSearch"
        />
      </div>

      <div class="listContainer">
        <div class="listHeader">
          <span style="min-width: 32.5rem; font-size: 1rem; color: #4f4f4f;">
            名称
          </span>
          <span style="min-width: 18.75rem; font-size: 1rem; color: #4f4f4f;">
            类别
          </span>
          <span style="min-width: 18.75rem; font-size: 1rem; color: #4f4f4f;">
            加工状态
          </span>
          <span style="min-width: 18.75rem; font-size: 1rem; color: #4f4f4f;">
            上传时间
          </span>
          <!-- <span style="min-width: 18.75rem; font-size: 1rem; color: #4f4f4f;">
            操作
          </span> -->
        </div>

        <a-list :data-source="data">
          <div v-for="item in data" :key="item.resourceId">
            <a-list-item
              class="listItem"
              @click="handleItemClickResource(item)"
            >
              <div style="min-width: 32rem" class="courseInfo">
                <img :src="getStatusIcon(item.webName ? '网页' : item.tag)" alt="课程图标" class="icon">
                <span class="courseText">{{ item.name || item.webName }}</span>
              </div>
              <div class="courseTag" style="min-width: 18.75rem;">
                <a-tag style="font-size: 1.125rem; border: none">
                  {{ item.tag }}
                </a-tag>
              </div>
              <div style="min-width: 19rem;">
                <template v-if="item.tag === '文档'">
                  <!-- 文档加工状态 -->
                  <template
                    v-if="!item.ossWriteStatus && !item.ragCompleteStatus && !item.smartTextStatus && item.handleCompleteStatus"
                  >
                    <LoadingOutlined spin style="color: #FFB64C; font-size: 1.25rem; margin-right: 0.5rem;" />
                    <span style="font-size: 1.125rem;">上传中</span>
                  </template>
                  <template
                    v-else-if="item.ossWriteStatus && !item.ragCompleteStatus && !item.smartTextStatus && !item.handleCompleteStatus"
                  >
                    <SyncOutlined style="color: #84E17E; font-size: 1.25rem; margin-right: 0.5rem;" />
                    <span style="font-size: 1.125rem;">加工中</span>
                  </template>
                  <template
                    v-else-if="item.ossWriteStatus && item.ragCompleteStatus && !item.smartTextStatus && !item.handleCompleteStatus"
                  >
                    <SyncOutlined style="color: #84E17E; font-size: 1.25rem; margin-right: 0.5rem;" />
                    <span style="font-size: 1.125rem;">加工中</span>
                  </template>
                  <template
                    v-else-if="item.ossWriteStatus && item.ragCompleteStatus && item.smartTextStatus && item.handleCompleteStatus"
                  >
                    <FileDoneOutlined style="color: #868AF6; font-size: 1.25rem; margin-right: 0.5rem;" />
                    <span style="font-size: 1.125rem;">加工成功</span>
                  </template>
                  <template
                    v-else-if="item.handleCompleteStatus && (!item.ossWriteStatus || !item.ragCompleteStatus || !item.smartTextStatus)"
                  >
                    <CloseCircleOutlined style="color: #FF4D4F; font-size: 1.25rem; margin-right: 0.5rem;" />
                    <span style="font-size: 1.125rem;">加工失败</span>
                  </template>
                </template>

                <!-- 音视频加工状态 -->
                <template v-else-if="item.tag === '音视频'">
                  <template
                    v-if="item.ossWriteStatus && item.transcriptionComplete && item.transcriptionCompleteStatus"
                  >
                    <FileDoneOutlined style="color: #868AF6; font-size: 1.25rem; margin-right: 0.5rem;" />
                    <span style="font-size: 1.125rem;">加工成功</span>
                  </template>
                  <template v-else-if="!item.transcriptionComplete && !item.transcriptionCompleteStatus">
                    <SyncOutlined style="color: #84E17E; font-size: 1.25rem; margin-right: 0.5rem;" />
                    <span style="font-size: 1.125rem;">加工中</span>
                  </template>
                  <template v-else>
                    <CloseCircleOutlined style="color: #FF4D4F; font-size: 1.25rem; margin-right: 0.5rem;" />
                    <span style="font-size: 1.125rem;">加工失败</span>
                  </template>
                </template>
                <span v-else style="font-size: 1.125rem;">{{ item.status }}</span>
              </div>
              <div class="updatedAt" style="min-width:19.5rem;">
                {{ item.createdAt }}
              </div>
              <!-- <div class="actions">
                <EyeOutlined style="color: #81838F; font-size: 1.25rem" />
              </div> -->
            </a-list-item>
          </div>
        </a-list>
      </div>
    </a-spin>
  </div>
</template>

<style scoped lang="scss">
.courseManager {
  background-color: rgb(255, 255, 255);
  padding-right: 1.25rem;
  height: calc(100vh - 6.25rem);
  overflow-y: hidden;
  overflow-x: auto;

  .title {
    font-size: 1.25rem;
    margin-bottom: 1.25rem;
  }

  .controlc {
    display: flex;
    justify-content: space-between;
    margin-bottom: 1.25rem;
  }

  .controls {
    display: flex;
    margin-bottom: 1.25rem;

    .search {
      width: 18.75rem;
    }
  }

  .listHeader {
    display: flex;
    font-weight: bold;
    padding: 1rem 0;
    background-color: #fff;
    border-bottom: 1px solid rgba(187, 187, 187, 1);
    position: sticky; /* 吸顶效果 */
    top: 0; /* 吸附在顶部 */
    z-index: 10; /* 确保它在其他内容之上 */
  }
  .listContainer {
  height: calc(100vh - 100px); /* 设置内容区高度，确保滚动效果 */
  overflow-y: auto;
  overflow-x: hidden;
}
  .listItem {
    display: flex;
    justify-content: flex-start;
    border-bottom: 1px solid rgba(187, 187, 187, 1);
    align-items: center;
    padding: 1.25rem 0;
    cursor: pointer;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;

    &:hover {
      background-color: #fafafa;

      .actions {
        opacity: 1;
      }
    }

    .courseInfo {
      display: flex;
      align-items: center;

      .icon {
        width: 24px;
        height: 24px;
        margin-right: 10px;
      }

      .courseText {
        white-space: nowrap;
        font-size: 1.125rem;
        overflow: hidden;
        text-overflow: ellipsis; /* 溢出部分显示省略号 */
        display: inline-block; /* 确保元素是块状或内联块状，这样可以设置宽度 */
        max-width: 25.375rem; /* 限制最大宽度为300px */
      }
    }

    .actions {
      display: flex;
      gap: 20px;
      opacity: 1; /* 默认隐藏 */
    }

    .updatedAt {
      font-size: 1.125rem;
    }
  }
}
</style>
